<template>
  <div class="app-container">
    <div style="display: flex;margin-bottom: 20px">
      <el-button v-waves :loading="downloadLoading" style="background-color: #4ab7bd;border-color: #4ab7bd"
        class="filter-item" type="primary" icon="el-icon-download">
        <a href="https://sgmwstoragefile.blob.core.chinacloudapi.cn/document/供应商用户信息上传模板20191008152344.xlsx"
          target="_blank">请先下载供应商信息上传模板</a>
      </el-button>
      <span style="text-align: center;margin-top: 15px;margin-left: 20px;">导入用户默认密码：P@ssw0rd</span>
    </div>
    <div>
      <el-input style="width: 70%;float: left;" size="small" v-model="ResourceUrl" placeholder="教学平台用户信息" />
      <el-upload class="avatar-uploader" :action="actionUrl" :show-file-list="false" :on-success="handleMainSuccess"
        :before-upload="beforeMainUpload">
        <el-button type="primary" :loading="loading" size="small">点击上传</el-button>
      </el-upload>
    </div>
    <div style="margin-top: 15px; display: flex;align-items: center">
      <span style="color: #FF0000;margin-left: 30px">失败总记录条数：{{ failItemCount }}</span>
    </div>
    <div v-if="failUrl!='#'" style="margin-top: 15px; margin-left: 30px;">
      <el-button type="primary"><a :href="failUrl" target="_blank">导出失败用户列表</a></el-button>
    </div>
    <div style="margin-top: 15px; margin-left: 30px;">
      <span style="color: #FF0000">上传失败数据列表(默认显示前100条)：</span>
    </div>
    <el-table v-loading="listLoading" :key="tableKey" :data="list" fit border highlight-current-row
      style="width: 100%;margin-top:20px;" height="250">
      <el-table-column label="登录名" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.LoginName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center">
        <template slot-scope="scope"><span>{{ scope.row.MobilePhone }}</span></template>
      </el-table-column>
      <el-table-column label="用户名" align="center">
        <template slot-scope="scope">
          <span> <span>{{ scope.row.UserName }}</span></span>
        </template>
      </el-table-column>
      <el-table-column label="失败原因" show-overflow-tooltip align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.Remark }}</span>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>


<script>
  import { insertAdminUsers } from "@/api/user";
  import waves from "@/directive/waves"; // Waves directiv
  import BackToTop from "@/components/BackToTop";

  export default {
    name: "ISVInfoUpload",
    components: { BackToTop },
    watch: {
      dateText(val) {
        this.list = [];
        this.ResourceUrl = ''
        this.loading = false
        this.failItemCount = 0
        this.failUrl = '#'
      }
    },
    props: {
      dateText: String
    },
    directives: { waves },
    data() {
      return {
        apiPre: process.env.VUE_APP_BASE_API,
        actionUrl: '',
        ResourceUrl: '',
        failUrl: '#',
        studentList: [],
        userType: "ISV",
        downloadLoading: false,
        loading: false,
        list: [],
        listLoading: false,
        tableKey: 0,
        allItemCount: 0,
        successItemCount: 0,
        failItemCount: 0,
        filterVal: [
          "姓名",
          "登录名",
          "职务",
          "移动电话",
          "邮箱",
          "性别",
          "出生日期",
          "个人简介"
        ],
        tHeader: [
          "姓名",
          "登录名",
          "职务",
          "移动电话",
          "邮箱",
          "性别",
          "出生日期",
          "个人简介"
        ]
      };
    },
    created() {
      this.actionUrl = this.apiPre + '/user/InsertISVAdminUsers'
    },
    methods: {
      formatJson(filterVal, jsonData) {
        return jsonData//.map(v => filterVal.map(j => v[j]));
      },
      handleMainSuccess(res, file) {//资源上传完成响应方法      
        this.loading = false
        if (res && res.code != 200) {
          this.$notify({
            title: "失败",
            message: "上传失败!",
            type: "error",
            duration: 3000
          });
          return
        }
        this.list = res.data.list.failed;
        this.failUrl = res.data.url
        this.failItemCount = res.data.list.failedCount;
        this.$notify({
          title: "成功",
          message: "上传完成!",
          type: "success",
          duration: 3000
        });
        this.loading = false
      },
      beforeMainUpload(file) {
        this.loading = true
        var fileName = file.name || ''
        var ext = fileName.split('.')[fileName.split('.').length - 1]
        if (ext !== "xls" && ext !== "xlsx" && ext !== "csv") {
          this.$notify({
            title: "失败",
            message: "上传资源只能是 xls/xlsx/csv 格式!",
            type: "error",
            duration: 3000
          });
          this.loading = false
          return false
        }
        const isLt5M = file.size / 1024 / 1024 < 5;
        if (!isLt5M) {
          this.$notify({
            title: "失败",
            message: "上传文件大小不能超过 5MB!",
            type: "error",
            duration: 3000
          });
          this.loading = false
          return false
        }
        this.ResourceUrl = fileName
      },
      handleDownload() {
        this.downloadLoading = true;
        import("@/vendor/Export2Excel").then(excel => {
          excel.export_json_to_excel({
            header: this.tHeader,
            data: [],
            filename: "教学平台平台用户信息上传模板"
          });
          setTimeout(() => {
            this.downloadLoading = false;
          }, 2000);
        });
      },
      beforeUpload(file) {
        var fileName = file.name || ''
        var ext = fileName.split('.')[fileName.split('.').length - 1]
        if (ext !== "xls" && ext !== "xlsx" && ext !== "csv") {
          this.$notify({
            title: "失败",
            message: "上传资源只能是 xls/xlsx/csv 格式!",
            type: "error",
            duration: 3000
          });
          return false
        }
        const isLtnM = file.size / 1024 / 1024 < 100;
        if (!isLtnM) {
          this.$notify({
            title: "失败",
            message: "上传资源大小不能超过100MB!",
            type: "error",
            duration: 3000
          });
          return false
        }
        return true
      },
      handleSuccess({ results, header }) {
        // results.forEach((item, index) => {
        //   const student = {};
        //   Object.keys(item).forEach(key => {
        //     if (key === "sno") {
        //       student.sno = String(item[key]);
        //     }
        //     if (key === "stuName") {
        //       student.stuName = item[key];
        //     }
        //     if (key === "stuSex") {
        //       student.stuSex = item[key];
        //     }
        //   });
        //   this.studentList.push(student);
        // });
        //this.studentList = results;
        console.log(results)
        this.insertStudentInfoList(results);
      },
      //插入数据库学生信息表
      async insertStudentInfoList(data) {
        this.listLoading = true;
        const result = await insertAdminUsers(data, this.userType);
        if (result.code === 200) {
          this.list = result.data.list.failed;
          this.allItemCount = data.length;
          this.successItemCount = result.data.list.succeed.length;
          this.failItemCount = result.data.list.failed.length;

          this.$notify({
            title: "成功",
            message: result.data.msg,
            type: "success",
            duration: 3000
          });
          this.listLoading = false;
        } else {
          this.list = result.data.list.failed;
          this.allItemCount = data.length;
          this.successItemCount = result.data.list.succeed.length;
          this.failItemCount = result.data.list.failed.length;

          this.$notify({
            title: "失败",
            message: result.data.msg,
            type: "error",
            duration: 3000
          });
          this.listLoading = false;
        }
      }
    }
  };
</script>


<style lang="stylus" type="text/stylus" rel="stylesheet/stylus" scoped></style>